/* 基于webgl图形库的渲染类 */

export class Renderer {
    static createProgram(gl: WebGLRenderingContext, vertexShaderSource: string, fragmentShaderSource: string): (WebGLProgram | null) {
        let program = <WebGLProgram>gl.createProgram();
        let vertexShader = Renderer.createShader(gl, vertexShaderSource, gl.VERTEX_SHADER)
        let fragmentShader = Renderer.createShader(gl, fragmentShaderSource, gl.FRAGMENT_SHADER)
        gl.attachShader(program, vertexShader)
        gl.attachShader(program, fragmentShader)
        gl.linkProgram(program);
        if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
            let info = gl.getProgramInfoLog(program);
            console.error("Could not link WebGL program. \n\n" + info);
            gl.deleteProgram(program)
            return null;
        }
        gl.deleteShader(fragmentShader);
        gl.deleteShader(vertexShader);
        return program;
    }
    static createShader(gl: WebGLRenderingContext, sourceCode: string, type: GLenum): WebGLShader {
        let shader = <WebGLShader>gl.createShader(type);
        gl.shaderSource(shader, sourceCode);
        gl.compileShader(shader);
        // console.log(gl.getShaderParameter(shader, gl.COMPILE_STATUS))
        if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
            let info = gl.getShaderInfoLog(shader);
            console.error("Could not compile WebGL program. \n\n" + info);
            gl.deleteShader(shader);
        }
        return shader;
    }
}



